package cn.virens.web.components.session.resolver;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.session.web.http.CookieHttpSessionIdResolver;
import org.springframework.session.web.http.HeaderHttpSessionIdResolver;
import org.springframework.session.web.http.HttpSessionIdResolver;

public class OrderHttpSessionIdResolver implements HttpSessionIdResolver {
	private List<HttpSessionIdResolver> resolvers = new ArrayList<>();

	public OrderHttpSessionIdResolver() {
		this.addResolver(new CookieHttpSessionIdResolver());
		this.addResolver(HeaderHttpSessionIdResolver.xAuthToken());
		this.addResolver(ParamHttpSessionIdResolver.newSessionIdResolver());
	}

	@Override
	public List<String> resolveSessionIds(HttpServletRequest request) {
		for (HttpSessionIdResolver resolver : resolvers) {
			List<String> answer = resolver.resolveSessionIds(request);

			if (CollectionUtils.isNotEmpty(answer)) { return answer; }
		}

		return Collections.emptyList();
	}

	@Override
	public void setSessionId(HttpServletRequest request, HttpServletResponse response, String sessionId) {
		for (HttpSessionIdResolver resolver : resolvers) {
			resolver.setSessionId(request, response, sessionId);
		}
	}

	@Override
	public void expireSession(HttpServletRequest request, HttpServletResponse response) {
		for (HttpSessionIdResolver resolver : resolvers) {
			resolver.expireSession(request, response);
		}
	}

	public List<HttpSessionIdResolver> getResolvers() {
		return resolvers;
	}

	public void addResolver(HttpSessionIdResolver resolver) {
		if (resolvers == null) {
			this.resolvers = new ArrayList<>();
		}

		resolvers.add(resolver);
	}

	public void setResolvers(List<HttpSessionIdResolver> resolvers) {
		this.resolvers = resolvers;
	}

}
